package com.tbit.uqbike.service.business.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbit.common.config.OssDefaultConfig;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.AccountGif;
import com.tbit.uqbike.object.pojo.OssConfig;
import com.tbit.uqbike.object.pojo.vo.AccountGifVO;
import com.tbit.uqbike.service.business.AccountGifService;
import com.tbit.uqbike.webmanager.dao.core.AccountDao;
import com.tbit.uqbike.webmanager.dao.core.AccountGifDao;
import com.tbit.uqbike.webmanager.dao.core.OssConfigDao;
import com.tbit.uqbike.webmanager.util.FileLoadUtils;
import com.tbit.uqbike.webmanager.util.aliyun.OssFileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

/**
 * @author yee_
 * @version 1.0
 * @date 2023/3/8 11:09
 */
@Service
public class AccountGifServiceImpl extends ServiceImpl<AccountGifDao, AccountGif> implements AccountGifService {

    @Resource
    private OssDefaultConfig ossDefaultConfig;
    @Resource
    private OssConfigDao ossConfigDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private AccountGifDao accountGifDao;

    @Override
    public boolean save(AccountGifVO vo) {
        Integer accountId = vo.getAccountId();
        MultipartFile image = vo.getImage();
        if (!FileLoadUtils.checkFileSize(image, 2, "M")) {
            throw new BaseException(SystemCodeEnum.IMAGE_SIZE_LIMIT2M);
        }
        Integer brandId = accountDao.getBrandIdByAccountId(accountId, 3);
        OssConfig ossConfig = Optional.ofNullable(brandId)
                .map(ossConfigDao::getByAccountId)
                .orElseGet(() -> new OssConfig(ossDefaultConfig.getEndpoint(),
                        ossDefaultConfig.getAccessKeyId(),
                        ossDefaultConfig.getAccessKeySecret(), "gx-res"));
        String fileUrl = OssFileUtils.upload(image, ossConfig);
        AccountGif accountGif = new AccountGif();
        accountGif.setAccountId(accountId);
        accountGif.setGifType(vo.getGifType());
        accountGif.setTitle(vo.getTitle());
        accountGif.setImageUrl(fileUrl);
        accountGif.setAddTime(new Date());
        accountGif.setRemark(vo.getRemark());
        accountGifDao.insert(accountGif);
        return false;
    }


}
